package xyz.hzxiao.option.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.hzxiao.entity.option.OptionsEntity;
import xyz.hzxiao.option.mapper.OptionsMapper;
import xyz.hzxiao.option.service.OptionsService;
import xyz.hzxiao.result.JsonResult;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author FuXx
 * @since 2024-12-04
 */
@Service
public class OptionsServiceImpl extends ServiceImpl<OptionsMapper, OptionsEntity> implements OptionsService {

    @Override
    public JsonResult<List<OptionsEntity>> queryOpeionList(String fatherId) {
        return JsonResult.ok(formTreeList2(this.list(new LambdaQueryWrapper<OptionsEntity>()
                .eq(Objects.nonNull(fatherId), OptionsEntity::getFatherOptionNumber, fatherId))));
    }

    private List<OptionsEntity> formTreeList(List<OptionsEntity> menuList) {
        return menuList.stream()
                .filter(e -> "T".equals(e.getFatherOptionNumber()))
                .flatMap(e -> {
                    e.setSubOptionList(menuList.stream()
                            .filter(el -> e.getOptionNumber().equals(el.getFatherOptionNumber()))
                            .collect(Collectors.toList()));
                    return Stream.of(e);
                }).toList();
    }

    private List<OptionsEntity> formTreeList2(List<OptionsEntity> menuList) {
        return menuList.stream()
                .filter(e -> "T".equals(e.getFatherOptionNumber()))
                .flatMap(e -> {
                    e.setSubOptionList(getSubList(e.getOptionNumber(), menuList));
                    return Stream.of(e);
                }).toList();
    }

    private List<OptionsEntity> getSubList(String parentId, List<OptionsEntity> menuList) {
        return menuList
                .stream()
                .filter(e -> parentId.equals(e.getFatherOptionNumber()))
                .flatMap(e -> {
                    e.setSubOptionList(getSubList(e.getOptionNumber(), menuList));
                    return Stream.of(e);
                }).toList();
    }
}
